﻿package cz.dadul.adventure.model
{
	import cz.dadul.adventure.model.Element;
	import flash.display.*;
	
	/**
	 * ...
	 * @author Dadul
	 */
	public class MainLayer extends Layer {
		public static const BACK_LAYER:int = 0;	
		public static const FRONT_LAYER:int = 2;
		
		private var _back:Sprite = new Sprite();
		private var _front:Sprite = new Sprite();
		private var _playerAdded:Boolean = false;
	
		public function MainLayer(name:String, mc:MovieClip = null) 
		{
			// Add standard graphics
			super(name, mc);
		}
		
		protected override function init():void {
			super.init();
			// Create
			this._layers[BACK_LAYER] = _back;
			this._layers[FRONT_LAYER] = _front;
			// Adds three super-layers to the display
			_back.name = "Backlayer";
			_front.name = "Frontlayer";
			addChild(_back);
			addChild(_front);			
		}
		
		public function addPlayer(p:Player, x:int = 0, y:int = 0, layerType:int = STANDARD_LAYER):Player {
			if (_playerAdded) {
				throw new Error("Player["+p.name+"] has been already added!");
			}
			_playerAdded = true;
			return addElement(p, x, y, layerType) as Player;
		}
		
		
		
		/**
		 *  Check depth dependency based on the players depth
		 *  - performed in the STANDARD_LAYER
		 *  - expects player in the _standard layer
		 */
		public function checkDepths(p:Player):void {			
			var stackedEl:Element;
			
			for (var i:int = 0; i < this._standard.numChildren; i++) {
				stackedEl = this._standard.getChildAt(i) as Element;
				
				if (stackedEl != p)  {
					// Move to the front
					if ( ( p.y >= stackedEl.y ) && ( this._standard.getChildIndex(p) < i) ) {						
						this._standard.removeChild(p);
						this._standard.addChildAt(p, i);
						break;
					}
					// Move to the back
					if ( ( p.y < stackedEl.y ) && ( this._standard.getChildIndex(p) > i) ) {
						this._standard.removeChild(p);
						this._standard.addChildAt(p, i);
						break;
					}
					
				}
			}
		}
		
		
	}
		
}